/**
 * 操作日志管理模块
 * 负责操作日志的显示、筛选、分页等功能
 */

// 操作日志管理器
const operationLogsManager = {
    currentPage: 1,
    pageSize: 8, // 默认值，将被动态计算覆盖
    totalCount: 0,
    currentFilters: {
        operationType: "DEVICE_CONTROL" // 默认只显示设备控制类型的日志
    },
    autoRefreshTimer: null, // 自动刷新定时器

    // 初始化
    init() {
        console.log('初始化操作日志管理器...');

        // 绑定刷新按钮事件
        const refreshBtn = document.getElementById('refresh-logs-btn');
        if (refreshBtn) {
            refreshBtn.addEventListener('click', () => this.refresh());
        }

        // 添加窗口大小变化监听器
        window.addEventListener('resize', this.debounce(() => {
            console.log('窗口大小变化，重新计算并加载');
            this.calculateAndSetLayout();
            this.loadLogs(1); // 重新从第一页加载
        }, 250));

        // 延迟执行，确保DOM布局稳定
        setTimeout(() => {
            this.calculateAndSetLayout();
            this.loadLogs(1);
            this.startAutoRefresh();
        }, 0);
    },

    // 启动自动刷新
    startAutoRefresh() {
        // 如果已经有定时器，先清除
        this.stopAutoRefresh();
        
        console.log('启动操作日志自动刷新');
        this.autoRefreshTimer = setInterval(() => {
            this.refresh();
        }, 10000);
    },

    // 停止自动刷新
    stopAutoRefresh() {
        if (this.autoRefreshTimer) {
            console.log('停止操作日志自动刷新');
            clearInterval(this.autoRefreshTimer);
            this.autoRefreshTimer = null;
        }
    },

    // 计算并设置容器高度和页面大小
    calculateAndSetLayout() {
        try {
            const tableContainer = document.querySelector('.logs-table-container');
            if (!tableContainer) {
                console.warn('未找到 .logs-table-container, 无法计算布局');
                this.pageSize = 8;
                return;
            }

            const viewportHeight = window.innerHeight;
            const tableRect = tableContainer.getBoundingClientRect();
            const tableTop = tableRect.top;

            const paginationContainer = document.getElementById('logs-pagination');
            // 在初始计算时，分页组件可能尚未渲染，其 offsetHeight 可能为 0。
            // 我们需要一个可靠的高度值。如果实际高度不可用或太小，则使用一个合理的默认值。
            let paginationHeight = 60; // 默认分页组件高度
            if (paginationContainer && paginationContainer.offsetHeight > 10) {
                paginationHeight = paginationContainer.offsetHeight;
            }
            
            // 预留20px的底部外边距，确保内容不会紧贴分页器
            const bottomMargin = 20;

            // 计算表格容器应该占据的可用高度
            const availableHeight = viewportHeight - tableTop - paginationHeight - bottomMargin;

            if (availableHeight < 150) { // 可用空间过小时的保护
                console.warn(`可用高度过小 (${availableHeight}px), 使用最小高度 150px`);
                tableContainer.style.height = '150px'; 
                this.pageSize = 3; // 同时设置一个较小的pageSize
                return;
            }
            
            // 估算行高和表头高
            const tableHeader = document.querySelector('#operation-logs-table thead');
            const headerHeight = tableHeader ? tableHeader.offsetHeight : 40;
            let rowHeight = 50; 
            const sampleRow = document.querySelector('#operation-logs-table tbody tr:not(.empty-list)');
            if (sampleRow) {
                // 使用 getBoundingClientRect().height 获取更精确的浮点数高度
                const rowRect = sampleRow.getBoundingClientRect();
                if (rowRect.height > 1) {
                    rowHeight = rowRect.height;
                }
            }
    
            // 基于可用空间计算可以容纳多少行
            const availableRowAreaHeight = availableHeight - headerHeight;
            const rowCount = Math.floor(availableRowAreaHeight / rowHeight);
            this.pageSize = Math.max(1, rowCount);

            // 关键：根据行数，计算出完美的容器高度，以消除内部空白
            const perfectContainerHeight = headerHeight + (this.pageSize * rowHeight);
            tableContainer.style.height = `${perfectContainerHeight}px`;
            tableContainer.style.overflowY = 'hidden'; 
            
            console.log(`布局计算完成: 完美容器高度=${perfectContainerHeight.toFixed(2)}px, 每页行数=${this.pageSize}, 行高=${rowHeight.toFixed(2)}px`);

        } catch (error) {
            console.error('计算布局出错:', error);
            this.pageSize = 8; // 出错时回退到默认值
        }
    },

    // 初始化分页组件
    initPagination() {
        const container = document.getElementById('logs-pagination');
        if (!container) return;
        container.innerHTML = ''; // 清空容器，确保重新创建

        if (window.PaginationComponent) {
            const options = {
                containerId: 'logs-pagination',
                currentPage: this.currentPage,
                totalCount: this.totalCount,
                pageSize: this.pageSize,
                theme: 'compact',
                onPageChange: (page) => {
                    this.loadLogs(page);
                }
            };
            this.pagination = window.PaginationComponent.create(options);
            // 将选项存储在实例上，以便将来进行比较
            this.pagination.options = options;
        }
    },

    // 加载日志列表
    async loadLogs(page = 1) {
        try {
            console.log(`加载操作日志，页码: ${page}, 每页: ${this.pageSize}`);
            this.currentPage = page;
            
            // 在分页器尚未初始化时，先根据当前pageSize进行初始化
            if (!this.pagination) {
                this.initPagination();
            }

            // 检查是否使用模拟数据
            if (shouldUseMockData()) {
                console.log('使用模拟数据获取操作日志');
                const result = window.MockOperationLogsData.getOperationLogs(
                    page,
                    this.pageSize,
                    this.currentFilters
                );

                if (result.success) {
                    const logsList = result.data.list || result.data.logs || [];
                    this.renderLogsList(logsList);
                    this.updatePagination(result.data.totalCount || 0, page);
                } else {
                    this.renderLogsList([]);
                    this.updatePagination(0, page);
                }
                return;
            }
            
            // 准备请求参数
            const params = {
                page: page,
                pageSize: this.pageSize,
                ...this.currentFilters
            };
            
            console.log('请求操作日志参数:', params);
            
            // 调用Android接口获取日志列表
            const response = await callAndroidMethodAsync('getOperationLogs', params);
            
            if (response.success && response.data) {
                const list = response.data.list;
                if (list) {
                    console.log(`获取到${list.length}条日志记录，总记录数: ${response.data.totalCount || 0}`);
                    this.renderLogsList(list);
                    this.updatePagination(response.data.totalCount || 0, page);
                } else {
                    console.error('获取日志列表失败: 无数据');
                    this.renderLogsList([]);
                    this.updatePagination(0, page);
                }
            } else {
                console.error('获取日志列表失败:', response.message);
                this.renderLogsList([]);
                this.updatePagination(0, page);
            }
        } catch (error) {
            console.error('加载日志列表出错:', error);
            this.renderLogsList([]);
            this.updatePagination(0, page);
        }
    },

    // 渲染日志列表
    renderLogsList(logs) {
        const tableBody = document.getElementById('logs-table-body');
        if (!tableBody) return;
        
        if (!logs || logs.length === 0) {
            tableBody.innerHTML = '<tr><td colspan="6" class="empty-list">暂无数据</td></tr>';
            return;
        }
        
        const html = logs.map(log => `
            <tr>
                <td>${this.escapeHtml(log.username || '')}</td>
                <td>${this.escapeHtml(log.operationDescription)}</td>
                <td>${this.escapeHtml(log.operationTimeString || '')}</td>
                <td style="display: none;">${log.operationType || ''}</td>
                <td>
                    <span class="status-badge ${log.operationStatus === 'SUCCESS' ? 'success' : 'error'}">
                        ${log.operationStatus === 'SUCCESS' ? '成功' : '失败'}
                    </span>
                </td>
                <td>
                    ${(log.operationStatus === 'FAILURE' || log.operationStatus === 'FAILED') && log.errorMessage ?
                `<span class="error-message" title="${this.escapeHtml(log.errorMessage)}">${this.escapeHtml(log.errorMessage.substring(0, 20))}${log.errorMessage.length > 20 ? '...' : ''}</span>` :
                '-'
            }
                </td>
            </tr>
        `).join('');
        
        tableBody.innerHTML = html;
    },

    // 更新分页信息
    updatePagination(totalCount, currentPage) {
        this.totalCount = totalCount;
        this.currentPage = currentPage;
        
        // 如果分页组件不存在，或pageSize已更改，则重新创建它
        if (!this.pagination || (this.pagination.options && this.pagination.options.pageSize !== this.pageSize)) {
            this.initPagination();
        }
        
        if (this.pagination) {
            // 只需更新变化的部分
            this.pagination.update({
                currentPage: currentPage,
                totalCount: totalCount
            });
        }
    },

    // 刷新数据
    refresh() {
        console.log('刷新操作日志数据...');
        this.loadLogs(this.currentPage);
    },

    // HTML转义
    escapeHtml(text) {
        if (!text) return '';
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    },
    
    // 防抖函数
    debounce(func, wait) {
        let timeout;
        return function(...args) {
            const later = () => {
                clearTimeout(timeout);
                func.apply(this, args);
            };
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
        };
    }
};

/**
 * 处理操作日志tab被激活
 * 在tab切换时调用此函数
 */
function activateOperationLogsTab() {
    console.log('操作日志tab被激活');
    // 初始化操作日志管理器
    operationLogsManager.init();
}

/**
 * 处理操作日志tab被隐藏
 * 在tab切换离开时调用此函数
 */
function deactivateOperationLogsTab() {
    console.log('操作日志tab被隐藏');
    // 停止自动刷新
    operationLogsManager.stopAutoRefresh();
}

// 全局暴露
window.operationLogsManager = operationLogsManager;
window.activateOperationLogsTab = activateOperationLogsTab;
window.deactivateOperationLogsTab = deactivateOperationLogsTab; 